<?php
class Webkul_Marketplacepartner_Model_Sellerpayment extends Mage_Core_Model_Abstract
{	 public function _construct() { 
       parent::_construct();       
	   $this->_init('marketplacepartner/sellerpayment');   
	   }

	public function salePayment($data)
	{
		$wholedata=$data->getParams('');
		$collection = Mage::getModel('marketplacepartner/sellerpayment')->getCollection();
		$collection->getSelect()->where('mageuserid ='.$wholedata['ID']);
		foreach ($collection as $verifyrow) {
		    $amountremain=$verifyrow->getamountremain();
			$amountpaid=$verifyrow->getamountpaid();
			$totalrecived=$amountremain+$amountpaid;
				$collection1 = Mage::getModel('marketplacepartner/sellerpayment')->load($wholedata['ID']);
				$collection1->setamountpaid($totalrecived);
				$collection1->setamountrecived($amountremain);
				$collection1->setamountremain(0);
				$collection1->save();
			return 0;
		}	
	}

	public function masssalePayment($data)
	{
		$wholedata=$data->getParams('');
		$collection = Mage::getModel('marketplacepartner/sellerpayment')->getCollection();
		foreach($wholedata['customer'] as $id) {
		$collection->getSelect()->where('mageuserid ='.$id);
		foreach ($collection as $verifyrow) {
		    $amountremain=$verifyrow->getamountremain();
			$amountpaid=$verifyrow->getamountpaid();
			$totalrecived=$amountremain+$amountpaid;
				$collection1 = Mage::getModel('marketplacepartner/sellerpayment')->load($id);
				$collection1->setamountpaid($totalrecived);
				$collection1->setamountrecived($amountremain);
				$collection1->setamountremain(0);
				$collection1->save();
			}
		}
			return 0;
	}
	
	public function saveSimpleNewProduct($wholedata){
		$status=Mage::getStoreConfig('partners/partners_options/partner_approval')? 2:1;
		$magentoProductModel = Mage::getModel('catalog/product');
		$magentoProductModel->setData($wholedata);
		$saved=$magentoProductModel->save();
		$magentoProductModel = Mage::getModel('catalog/product')->load($saved->getId());
		$magentoProductModel->setPrice($wholedata['price']);
		$magentoProductModel->setWeight($wholedata['weight']);
		$magentoProductModel->setWebsiteIds(array(Mage::app()->getStore()->getStoreId()));
		$magentoProductModel->setCategoryIds(Array($wholedata['category']));
		$magentoProductModel->setStatus($status);
		$magentoProductModel->setTaxClassId(0);
		$saved=$magentoProductModel->save();
		$lastId = $saved->getId();
		$custom = explode(",",$wholedata['customcountallid']);
		for($k=0;$k<$wholedata['customcount'];$k++){
			$cuarray=array();
			for($l=1;$l<=$wholedata['headchild'.$custom[$k]]; $l++)
			{
				$cuarray[$l]=array( 'is_delete' =>0,
						'title'         =>$wholedata['vcustomtitle'.$custom[$k].'cop'.$l],
						'price_type'    => $wholedata['vcustompricetype'.$custom[$k].'cop'.$l],
						'price'         => $wholedata['vcustomprice'.$custom[$k].'cop'.$l],
						 'sku'           => $wholedata['vcustomsku'.$custom[$k].'cop'.$l],
						 'sort_order'        => $wholedata['vcustomsort'.$custom[$k].'cop'.$l],
						'option_type_id'=> -1,
						);
			}
			$optionData    = array(	
							'is_require'        =>$wholedata['customrequired'.$custom[$k]],
							'previous_group'    => '',
							'title'             => $wholedata['customtitle'.$custom[$k]],
							'type'              => $wholedata['customtype'.$custom[$k]], //field,area,checkbox,radio etc drop_down
							'price_type'        => 'fixed',
							'price'             => 0,
							'sort_order'        => $wholedata['customsort'.$custom[$k]],
							'values'	=> $cuarray,
							);
					$magentoProductModel->setHasOptions(1)->save();
					$option = Mage::getModel('catalog/product_option')->setProductId($magentoProductModel->getId())->setStoreId($magentoProductModel->getStoreId())->addData($optionData);
					$option->save();
					$magentoProductModel->addOption($option);
					$magentoProductModel->save(); 
			
		}
		$this->_saveStock($lastId,$wholedata['stock']); 
		
		$collection1=Mage::getModel('marketplacepartner/userdata');
		$collection1->setmageproductid($lastId);
		$collection1->setuserid($wholedata['userid']);
		$collection1->setstatus($status);
		$collection1->save();
		if(isset($_FILES) && count($_FILES) > 0){
			if($wholedata['type_id']=='simple'){
				foreach($_FILES as $image ){
					if($image['tmp_name'] != ''){
						if (($error = $this->uploadImage1($image, $lastId)) !== true){
							$errors[] = $error;
						}
					}
				}
			}				
		}
		$this->_addImages($lastId);
		return $lastId;		
	}
	
	public function editApprovedProduct($data,$id,$wholedata){
		$productcity = Mage::getModel('catalog/product');
		$loadpro= $productcity->load($id);
		$loadpro->setData($wholedata);
		$saved=$loadpro->save();
		$loadpro = Mage::getModel('catalog/product')->load($saved->getId());
		$loadpro->setPrice($wholedata['price']);
		$loadpro->setWeight($wholedata['weight']);
		$loadpro->save();
		$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($id);
		$loadpro->save();
		$customcount = explode(',',$wholedata['customcountallid']);	
		if($customcount[0]>0){
			for($k=0; $k<count($customcount);$k++){
				$childcount= explode(',',$wholedata['childper'.$customcount[$k]]);
				$cuarray=array();
				for($l=0;$l<count($childcount); $l++){
					$cuarray[$l]=array( 'is_delete' =>0,
							'title'         =>$wholedata['vcustomtitle'.$customcount[$k].'cop'.$childcount[$l]],
							'price_type'    => $wholedata['vcustompricetype'.$customcount[$k].'cop'.$childcount[$l]],
							'price'         => $wholedata['vcustomprice'.$customcount[$k].'cop'.$childcount[$l]],
							'sku'           => $wholedata['vcustomsku'.$customcount[$k].'cop'.$childcount[$l]],
							'sort_order'    => $wholedata['vcustomsort'.$customcount[$k].'cop'.$childcount[$l]],
							'option_type_id'=> -1,
							);
				}
				$optionData = array(	
							'is_require'        =>$wholedata['customrequired'.$customcount[$k]],
							'previous_group'    => '',
							'title'             => $wholedata['customtitle'.$customcount[$k]],
							'type'              => $wholedata['customtype'.$customcount[$k]],
							'price_type'        => 'fixed',
							'price'             => 0,
							'sort_order'        => $wholedata['customsort'.$customcount[$k]],
							'values'	=> $cuarray,
							);
				$loadpro->setHasOptions(1)->save();
				$option = Mage::getModel('catalog/product_option')->setProductId($loadpro->getId())
															 ->setStoreId($loadpro->getStoreId())
															 ->addData($optionData);
				$option->save();
				$loadpro->addOption($option);
				$loadpro->save(); 
			}
		}
		if(!is_dir(Mage::getBaseDir().'/media/customersproducts/'.$id.'/')){
			mkdir(Mage::getBaseDir().'/media/customersproducts/'.$id.'/', 0755);
		}
		$target =Mage::getBaseDir().'/media/customersproducts/'.$id.'/';
		if(isset($_FILES) && count($_FILES) > 0){
			foreach($_FILES as $image ){
				if($image['tmp_name'] != ''){
					$target1 = $target.$image['name']; 
					move_uploaded_file($image['tmp_name'],$target1);
				}
			}				
		}
		$this->_addImages($id);
		$qtyStock->setProductId($id)->setStockId(1);
		$qtyStock->setData('is_in_stock', 1); 
		$savedStock = $qtyStock->save();
		$qtyStock->load($savedStock->getId())->setQty($data->getParam('stock'))->save();
		return 0;
	}
	public function deleteProduct($wholedata){
		$id = explode('/id/',$wholedata );
		Mage::register("isSecureArea", 1);
		$write = Mage::getSingleton('core/resource')->getConnection('core_write');
    	Mage :: app("default") -> setCurrentStore( Mage_Core_Model_App :: ADMIN_STORE_ID );
		Mage::getModel('catalog/product')->load($id[1])->delete();
		Mage::getModel('marketplacepartner/marketplacepartner_product')->load($id[1])->delete();
		$querydata=$write->query("delete from ".Mage::getConfig()->getTablePrefix()."marketplacepartner_entity_data where mageproductid='".$id[1]."'");
		return 0;
	}
	private function _saveStock($lastId,$stock){
		$stockItem = Mage::getModel('cataloginventory/stock_item');
		$stockItem->loadByProduct($lastId);
		if(!$stockItem->getId()){$stockItem->setProductId($lastId)->setStockId(1);}
		$stockItem->setData('is_in_stock', 1);
		$savedStock = $stockItem->save();
		$stockItem->load($savedStock->getId())->setQty($stock)->save();
	}
	
	private function uploadImage1($image, $product_id){
		$max_size = 3670016; // the max. size for uploading
		$my_upload = Mage::getModel('marketplaceprofile/uploadimage');
		if (!is_dir(Mage::getBaseDir().'/media/customersproducts/')){
			mkdir(Mage::getBaseDir().'/media/customersproducts/', 0755);
		}
		// "files" is the folder for the uploaded files
		$my_upload->upload_dir = Mage::getBaseDir().'/media/customersproducts/'.$product_id."/"; 
		$my_upload->extensions = array(".gif", ".jpg", ".jpeg",".png"); // specify the allowed extensions here
		$my_upload->max_length_filename = 100; // change this value to fit your field length in your database (standard 100)
		$my_upload->rename_file = false;
		$my_upload->the_temp_file = $image['tmp_name'];
		$my_upload->the_file = $image['name'];
		$my_upload->http_error = $image['error'];
		$my_upload->replace = true; // because only a checked checkboxes is true
		// use this boolean to check for a valid filename
		$my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "y"; 
		$new_name = (isset($_POST['name'])) ? $_POST['name'] : "";
		// new name is an additional filename information, use this to rename the uploaded file
		if($my_upload->upload($new_name)) {return true;} 
		else{return $my_upload->show_error_string();}
	}
	
	private function _addImages($objProduct){
		$mediDir = Mage::getBaseDir('media');
		$imagesdir = $mediDir . '/customersproducts/' . $objProduct . '/';
		if(!file_exists($imagesdir)){return false;}
		foreach (new DirectoryIterator($imagesdir) as $fileInfo){
    		if($fileInfo->isDot() || $fileInfo->isDir()) continue;
    		if($fileInfo->isFile()){
				$fileinfo=explode('@',$fileInfo->getPathname());
				$objprod=Mage::getModel('catalog/product')->load($objProduct);
				$objprod->addImageToMediaGallery($fileInfo->getPathname(), array ('image','small_image','thumbnail'), true, false);
				$objprod->save();					
				
    		}
		}
	}
	
	
}

?>